<?php

namespace app\store\model\dealer;

use app\store\model\dealer\Referee as RefereeModel;
use app\common\model\dealer\User as UserModel;

/**
 * 分销商用户模型
 * Class User
 * @package app\store\model\dealer
 */
class User extends UserModel
{
    /**
     * 获取分销商用户列表
     * @param string $search
     * @param string $start_time
     * @param string $end_time
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($search = '', $start_time = '', $end_time = '', $sortOrder = 'desc',$pagesite = 15)
    {
        // dump($start_time);
        // dump($end_time);die;
        // 子查询：统计累计推荐购买人数，关联 dealer_referee 表
        $subQuery = DB('dealer_referee')
            ->alias('dr') // 设置别名
            ->field('COUNT(*)')
            ->where('dr.dealer_id = dealer.user_id') // 分销商对应的推荐用户
            ->buildSql();

        // 子查询：获取 user_jiuzhen 表中的单条记录（按创建时间排序）
        $userJiuzhenSubQuery = DB('user_jiuzhen')
            ->alias('uj')
            ->field('uj.user_id, uj.name as jiuzhen_name, uj.phone as jiuzhen_phone, uj.create_time')
            ->where('uj.is_del', '=', 0)
            ->order('uj.create_time', 'asc') // 按创建时间升序获取最新记录
            ->buildSql();

        // 构建查询规则
        $this->alias('dealer')
            ->field('dealer.*, user.nickName, user.phone, user.avatarUrl, (' . $subQuery . ') as total_recommended, uj.jiuzhen_name, uj.jiuzhen_phone') // 统计推荐人数并关联就诊人信息
            ->with(['referee'])
            ->join('user', 'user.user_id = dealer.user_id') // 关联用户表
            ->join([$userJiuzhenSubQuery => 'uj'], 'uj.user_id = dealer.user_id', 'LEFT') // 关联 user_jiuzhen 的子查询
            ->where('dealer.is_delete', '=', 0);

        // 添加搜索条件
        if (!empty($search)) {
            $this->where('user.nickName|uj.jiuzhen_name|dealer.real_name|dealer.mobile|user.phone', 'like', "%$search%");
        }

        // 添加时间范围条件
        if (!empty($start_time) || !empty($end_time)) {
            $start_time = !empty($start_time) ? strtotime($start_time . ' 00:00:00') : 0;
            $end_time = !empty($end_time) ? strtotime($end_time . ' 23:59:59') : time();

            $this->where('dealer.create_time', 'between', [$start_time, $end_time]);
        }

        // 添加排序逻辑
        if (in_array($sortOrder, ['asc', 'desc'], true)) {
            $this->order(['total_recommended' => $sortOrder, 'dealer.create_time' => 'desc']);
        } else {
            $this->order(['dealer.create_time' => 'desc']);
        }

        // 获取列表数据
        return $this->paginate($pagesite, false, [
            'query' => \request()->request()
        ]);
    }
    public function getList1($search = '', $start_time = '', $end_time = '', $sortOrder = 'desc',$pagesite = 15)
    {
        // 子查询：统计累计推荐人数，关联 dealer_referee 表
        $subQuery = DB('dealer_referee')
            ->alias('dr')
            ->field('COUNT(*)')
            ->where('dr.dealer_id = dealer.user_id') // 关联条件
            ->buildSql();

        // 子查询：获取 user_jiuzhen 表中的单条记录（按创建时间排序）
        $userJiuzhenSubQuery = DB('user_jiuzhen')
            ->alias('uj')
            ->field('uj.user_id, uj.name as jiuzhen_name, uj.phone as jiuzhen_phone')
            ->where('uj.is_del', '=', 0)
            ->order('uj.create_time', 'asc') // 按创建时间升序获取最新记录
            ->buildSql();

        // 构建查询规则
        $this->alias('dealer')
            ->field('dealer.*, user.nickName, user.phone, user.avatarUrl, (' . $subQuery . ') as total_recommended, uj.jiuzhen_name, uj.jiuzhen_phone') // 统计推荐人数并关联就诊人信息
            ->with(['referee'])
            ->join('user', 'user.user_id = dealer.user_id') // 关联用户表
            ->join([$userJiuzhenSubQuery => 'uj'], 'uj.user_id = dealer.user_id', 'LEFT') // 关联 user_jiuzhen 表的子查询
            ->where('dealer.is_delete', '=', 0);

        // 添加搜索条件
        if (!empty($search)) {
            $this->where('user.nickName|uj.jiuzhen_name|dealer.real_name|dealer.mobile|user.phone', 'like', "%$search%");
        }

        // 添加时间范围条件
        if (!empty($start_time) || !empty($end_time)) {
            $start_time = !empty($start_time) ? strtotime($start_time . ' 00:00:00') : 0;
            $end_time = !empty($end_time) ? strtotime($end_time . ' 23:59:59') : time();

            $this->where('dealer.create_time', 'between', [$start_time, $end_time]);
        }

        // 动态排序：按下级数量正序或倒序排序
        $this->order([
            'total_recommended' => $sortOrder, // 动态设置正序或倒序
            'dealer.create_time' => 'desc'    // 创建时间降序作为备用排序
        ]);

        // 获取列表数据
        return $this->paginate($pagesite, false, [
            'query' => \request()->request()
        ]);
    }
    /**
     * 编辑分销商用户
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 删除分销商用户
     * @return mixed
     */
    public function setDelete()
    {
        return $this->transaction(function () {
            // 获取一级团队成员ID集
            $RefereeModel = new RefereeModel;
            $team1Ids = $RefereeModel->getTeamUserIds($this['user_id'], 1);
            if (!empty($team1Ids)) {
                // 一级团队成员归属到平台
                $this->setFromplatform($team1Ids);
                // 一级推荐人ID
                $referee1Id = RefereeModel::getRefereeUserId($this['user_id'], 1, true);
                if ($referee1Id > 0) {
                    // 一级推荐人的成员数量(二级)
                    $this->setDecTeamNum($referee1Id, 2, count($team1Ids));
                    // 一级推荐人的成员数量(三级)
                    $team2Ids = $RefereeModel->getTeamUserIds($this['user_id'], 2);
                    !empty($team2Ids) && $this->setDecTeamNum($referee1Id, 3, count($team2Ids));
                    // 二级推荐人的成员数量(三级)
                    $referee2Id = RefereeModel::getRefereeUserId($this['user_id'], 2, true);
                    $referee2Id > 0 && $this->setDecTeamNum($referee2Id, 3, count($team1Ids));
                    // 清空分销商下级成员与上级推荐人的关系记录
                    $RefereeModel->onClearTop(array_merge($team1Ids, $team2Ids));
                }
            }
            // 清空下级推荐记录
            $RefereeModel->onClearTeam($this['user_id']);
            // 标记当前分销商记录为已删除
            return $this->delete();
        });
    }

    /**
     * 一级团队成员归属到平台
     * @param $userIds
     * @return false|int
     */
    private function setFromplatform($userIds)
    {
        return $this->isUpdate(true)->save(
            ['referee_id' => 0],
            ['user_id' => ['in', $userIds], 'is_delete' => 0]
        );
    }

    /**
     * 删除用户的上级推荐关系
     * @param $userId
     * @return bool
     * @throws \think\Exception
     */
    public function onDeleteReferee($userId)
    {
        // 获取推荐人列表
        $list = RefereeModel::getRefereeList($userId);
        if (!$list->isEmpty()) {
            // 递减推荐人的下级成员数量
            foreach ($list as $item) {
                $item['dealer1'] && $this->setDecTeamNum($item['dealer_id'], $item['level'], 1);
            }
            // 清空上级推荐关系
            (new RefereeModel)->onClearReferee($userId);
        }
        return true;
    }

    /**
     * 递减分销商成员数量
     * @param $dealerId
     * @param $level
     * @param $number
     * @return int|true
     * @throws \think\Exception
     */
    private function setDecTeamNum($dealerId, $level, $number)
    {
        $field = [1 => 'first_num', 2 => 'second_num', 3 => 'third_num'];
        return $this->where('user_id', '=', $dealerId)
            ->where('is_delete', '=', 0)
            ->setDec($field[$level], $number);
    }

    /**
     * 提现打款成功：累积提现佣金
     * @param $user_id
     * @param $money
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function totalMoney($user_id, $money)
    {
        $model = self::detail($user_id);
        return $model->save([
            'freeze_money' => $model['freeze_money'] - $money,
            'total_money' => $model['total_money'] + $money,
        ]);
    }

    /**
     * 提现驳回：解冻分销商资金
     * @param $user_id
     * @param $money
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function backFreezeMoney($user_id, $money)
    {
        $model = self::detail($user_id);
        return $model->save([
            'money' => $model['money'] + $money,
            'freeze_money' => $model['freeze_money'] - $money,
        ]);
    }

}